package com.agen.basenet.converter;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 *
 * @author agen
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            T result = gson.fromJson(response, type);
            return result;
        } catch (JsonSyntaxException e) {
            if (type instanceof Class) {
                Class<?> clazz = (Class<?>) type;
                if (clazz == String.class) {
                    return (T) response;
                }
            }
            throw e;
        }
    }
}